//
//  SLLocationService.m
//  SulitLoan
//
//  Created by 虞嘉伟 on 2025/2/25.
//

#import "SLLocationService.h"
#import <CoreLocation/CoreLocation.h>

@interface SLLocationService ()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, copy  ) void(^completion)(CGFloat lat, CGFloat lon);
@end

@interface SLLocationService ()
@property (nonatomic, strong) SLLocationService *owner;
@end

@implementation SLLocationService

- (CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [CLLocationManager new];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    }
    return _locationManager;
}
- (void)retainSelf {
    self.owner = self;
}
- (void)releaseSelf {
    self.owner = nil;
    self.completion = nil;
}
+ (instancetype)startLocationWithCompletion:(void(^)(CGFloat lat, CGFloat lon))completion {
    SLLocationService *location = [SLLocationService new];
    location.completion = completion;
    [location retainSelf];
    [location requestLocationPermission];
    __weak typeof(location) weakLocation = location;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        CGFloat lat = [NSUserDefaults.standardUserDefaults doubleForKey:@"latitude"];
        CGFloat lon = [NSUserDefaults.standardUserDefaults doubleForKey:@"longitude"];
        !weakLocation.completion ?: weakLocation.completion(lat, lon);
    });
    return location;
}

- (CLAuthorizationStatus)authorizationStatus {
    if (@available(iOS 14.0, *)) {
        return self.locationManager.authorizationStatus;
    } else {
        return [CLLocationManager authorizationStatus];
    }
}
/// 请求权限
- (void)requestLocationPermission {
    CLAuthorizationStatus status = self.authorizationStatus;
    if (status == kCLAuthorizationStatusNotDetermined) {
        // 请求权限
        [self.locationManager requestWhenInUseAuthorization];
    } else if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        // 已经授权，直接获取定位
        [self.locationManager startUpdatingLocation];
    } else {
        // 权限被拒绝或受限
        NSLog(@"定位访问权限被拒绝或受限");
        //[self openAppSettingsAlert];
    }
}

- (void)openAppSettingsAlert {
    NSString *message = @"To ensure a smooth loan application process, SulitLoan accesses your location. Please go to \"Settings\" and enable location services for SulitLoan.";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Tip" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"Confirm" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openAppSettings];
    }];
    [alert addAction:action];
    UIViewController *ctrl = UIApplication.sharedApplication.keyWindow.rootViewController;
    [ctrl presentViewController:alert animated:YES completion:nil];
}
- (void)openAppSettings {
    NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:settingsURL]) {
        [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
    }
}

- (void)stopLocation {
    [self.locationManager stopUpdatingLocation];
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    // 获取最新的位置
    CLLocation *currentLocation = [locations lastObject];
    
    // 打印经纬度
    NSLog(@"Latitude: %f", currentLocation.coordinate.latitude); // 纬度
    NSLog(@"Longitude: %f", currentLocation.coordinate.longitude); // 经度
    [NSUserDefaults.standardUserDefaults setObject:@(currentLocation.coordinate.latitude) forKey:@"latitude"];
    [NSUserDefaults.standardUserDefaults setObject:@(currentLocation.coordinate.longitude) forKey:@"longitude"];
    
    // 停止更新位置（如果需要）
    [self.locationManager stopUpdatingLocation];
    
    !self.completion ?: self.completion(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
    [self releaseSelf];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    // 处理定位失败的情况
    NSLog(@"Failed to get location: %@", error.localizedDescription);
    !self.completion ?: self.completion(0, 0);
    [self releaseSelf];
}

/// 定位权限变化
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusAuthorizedAlways) {
        // 用户授权，开始更新位置
        [self.locationManager startUpdatingLocation];
    } else {
        // 用户拒绝授权，处理相应逻辑
        NSLog(@"Location access denied");
        !self.completion ?: self.completion(0, 0);
    }
}
@end
